<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="12">

          <a-col :md="4" :sm="8">
            <a-form-item label="车牌号">
              <a-input placeholder="请输入车牌号" v-model="queryParam.plateNo"></a-input>

            </a-form-item>
          </a-col>

          <a-col :md="4" :sm="8" v-has="'parkUser:add'">
            <a-form-item label="月租车类型">
              <a-select :options="CarTypeOptions" v-model="queryParam.carTypeId"></a-select>
            </a-form-item>
          </a-col>

          <a-col :md="4" :sm="8">
            <a-form-item label="起始时间">
              <a-date-picker placeholder="过期时间开始日期" @change="onChangeStartTime"/>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <a-form-item label="过期时间">
              <a-date-picker placeholder="过期时间结束日期" @change="onChangeEndTime"/>
            </a-form-item>
          </a-col>

          <a-col :md="4" :sm="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
            </span>
          </a-col>

        </a-row>
      </a-form>
    </div>
    <div class="table-operator">
      <!--      <a-button v-has="'parkUser:add'" @click="handleAdd" type="primary" icon="plus">新增</a-button>-->
      <a-button type="primary" icon="download" @click="handleExportXls('白名单')">导出</a-button>
      <!--      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel">
            <a-icon type="delete"/>
            删除
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作
          <a-icon type="down"/>
        </a-button>
      </a-dropdown>-->
    </div>

    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择<a
          style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        @change="handleTableChange"
        :scroll="{ x: 1400}"
        style="word-break: break-all"
      >

        <span slot="carTypeId" slot-scope="text,record">
          {{ translateCarTypeName(text) }}
        </span>

        <span slot="action" slot-scope="text, record">
          <a @click="handleDetail(record)">详情</a>
        </span>

      </a-table>
    </div>
    <ParkWhiteListModalDetail ref="detailForm"></ParkWhiteListModalDetail>
  </a-card>
</template>

<script>
import ParkWhiteListModal from './modules/ParkCarMonthlyModal'
import ParkWhiteListModalDetail from "./modules/ParkCarMonthlyModalDetail"
import {JeecgListMixin} from '@/mixins/JeecgListMixin'
import {deleteAction, getAction, downFile} from '@/api/manage'
import {filterObj} from '@/utils/util';


export default {
  name: "ParkWhiteListList",
  mixins: [JeecgListMixin],
  components: {
    ParkWhiteListModal,
    ParkWhiteListModalDetail,

  },
  data() {
    return {
      description: '白名单管理页面',
      operation: {
        delay: 'delay',
        edit: 'edit',
      },
      // 表头
      columns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 50,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: '停车场编号',
          align: "center",
          dataIndex: 'parkCode',
          width: 100
        },
        {
          title: '停车场名称',
          align: "center",
          dataIndex: 'parkName',
          width: 150
        },
        {
          title: '车牌号',
          align: "center",
          dataIndex: 'plateNo',
          width: 130
        },
        {
          title: "月租车类型",
          align: "center",
          dataIndex: 'carTypeId',
          width: 130,
          scopedSlots: {customRender: 'carTypeId'},
        },
        {
          title: '起始时间',
          align: "center",
          dataIndex: 'startTime',
          width: 150,
          customRender: function (t, r, index) {
            if (r.licenseType === 3) {
              return ''
            } else {
              return t
            }
          }
        },
        {
          title: '过期时间',
          align: "center",
          dataIndex: 'endTime',
          customRender: function (t, r, index) {
            if (r.licenseType === 3) {
              return ''
            } else {
              return t
            }
          },
          width: 150
        },
        {
          title: '客户姓名',
          align: "center",
          dataIndex: 'userName',
          width: 100
        },
        {
          title: '客户手机号码',
          align: "center",
          dataIndex: 'mobile',
          width: 150
        },
        {
          title: '所属车位',
          align: "center",
          dataIndex: 'parkNumber',
          width: 100
        },
        {
          title: '修改时间',
          align: "center",
          dataIndex: 'updateTime',
          width: 150
        },
        {
          title: '创建时间',
          align: "center",
          dataIndex: 'createTime',
          width: 150
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: "center",
          width: 100,
          scopedSlots: {customRender: 'action'},
        }
      ],
      url: {
        list: "/parkCar/parkCarMonthly/list",
        delete: "/parkCar/parkCarMonthly/delete",
        deleteBatch: "/parkCar/parkCarMonthly/deleteBatch",
        exportXlsUrl: "/parkCar/parkCarMonthly/ParkCarMonthlyExportXls",
        importExcelUrl: "/parkCar/parkCarMonthly/importExcel",
        carTypeList: "/ConfigCarType/configCarType/parkCarTypeList"
      },
      queryParam: {
        "endTime_begin": "",
        "endTime_end": "",
        "plateNo": "",
        "parkNumber": "",
        "carTypeId": "",
        "type": "-1",
      },
      isorter: {
        column: 'createTime',
        order: 'desc',
      },
      CarTypeOptions: [{value: '', label: '请选择车辆类型'}]
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    }
  },
  created() {
    this.keyupEnter()
    this.loadCarTypeOptions()
  },

  methods: {

    handleEdit: function (record, judge) {
      if (judge == this.operation.delay) {
        this.$refs.modalForm.edit(record, this.operation.delay);
        this.$refs.modalForm.title = "延期";
      } else {
        this.$refs.modalForm.edit(record, this.operation.edit);
        this.$refs.modalForm.title = "编辑";
      }
      this.$refs.modalForm.disableSubmit = false;
      this.$refs.modalForm.carTypes = JSON.parse(JSON.stringify(this.CarTypeOptions))
      if (this.CarTypeOptions.length > 1) {
        this.$refs.modalForm.carTypes.shift()
      }
    },
    handleAdd: function () {
      this.$refs.modalForm.add();
      this.$refs.modalForm.title = "新增";
      this.$refs.modalForm.disableSubmit = false;
      this.$refs.modalForm.carTypes = JSON.parse(JSON.stringify(this.CarTypeOptions))
      if (this.CarTypeOptions.length > 1) {
        this.$refs.modalForm.carTypes.shift()
        this.$refs.modalForm.defaultCarTypeId = this.$refs.modalForm.carTypes[0].value
      }
    },
    loadCarTypeOptions() {
      // const params = []
      // params.method = 'monthCar'
      getAction(this.url.carTypeList, { method: "monthCar" }).then((res) => {
        if (res.success && res.result.length > 0) {
          let index = 0
          const CarArray = [{value: '', label: '请选择车辆类型',key:'',index:index}]
          res.result.forEach((car) => {
            index++
            CarArray.push({
              index: index,
              key:index,
              value: car.id,
              label: car.carTypeName
            })
          })
          this.CarTypeOptions = CarArray
        }
      })
    },

    daysBetween(sDate1, sDate2) {
      let time1 = Date.parse(new Date(sDate1).toDateString());
      let time2 = Date.parse(new Date(sDate2).toDateString());
      let nDays = Math.abs(parseInt((time2 - time1) / 1000 / 3600 / 24));
      return nDays;
    },

    handleExportXls(fileName) {

      let param = {...this.queryParam};
      if (this.queryParam.endTime_begin !== "" && this.queryParam.endTime_end !== "") {
        param.endTime_begin = this.queryParam.endTime_begin + " 00:00:00";
        param.endTime_end = this.queryParam.endTime_end + " 23:59:59";
        param.plateNo = this.queryParam.plateNo;
      }
      if (this.queryParam.endTime_begin !== "" && this.queryParam.endTime_end === "") {
        this.$message.error("请选择结束时间")
        return
      }
      if (this.queryParam.endTime_begin === "" && this.queryParam.endTime_end !== "") {
        this.$message.error("请选择开始时间")
        return
      }
      if (this.queryParam.endTime_begin !== "" && this.queryParam.endTime_end !== "") {
        if (this.queryParam.endTime_begin > this.queryParam.endTime_end) {
          this.$message.error("开始时间不能大于结束时间");
          return
        }
      }

      downFile(this.url.exportXlsUrl, param).then((data) => {

        if (!data) {
          this.$message.warning("文件下载失败")
          return
        }
        if (data.size === 5632) {
          this.$message.warning("当前时段内没有月租车信息")
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data]), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);
        }
      })
    },

    onChangeStartTime(date, dateString) {
      this.queryParam.endTime_begin = dateString;
    },

    onChangeEndTime(date, dateString) {
      this.queryParam.endTime_end = dateString;
    },

    loadData(arg) {
      const that = this
      if (!this.url.list) {
        this.$message.error("请设置url.list属性!")
        return
      }
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      let params = this.getQueryParams();
      this.loading = true;
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          that.dataSource = res.result.records;
          that.ipagination.total = res.result.total;
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        that.loading = false;
      })
    },

    searchQuery() {
      let startTime = this.queryParam.endTime_begin;
      let endTime = this.queryParam.endTime_end;
      if (startTime !== "" && endTime !== "") {
        if (startTime > endTime) {
          this.$message.error("开始时间不能大于结束时间");
          return
        }
      }
      if (startTime === "" && endTime !== "") {
        this.$message.error("请选择开始时间");
        return
      }

      if (startTime !== "" && endTime === "") {
        this.$message.error("请选择结束时间");
        return
      }
      this.loadData(1);
    },
    getQueryParams() {
      var param = Object.assign({}, this.isorter, this.queryParam);
      param.field = this.getQueryField();
      param.pageNo = this.ipagination.current;
      param.pageSize = this.ipagination.pageSize;
      if (this.queryParam.endTime_begin !== "" && this.queryParam.endTime_end !== "") {
        param.endTime_begin = this.queryParam.endTime_begin + " 00:00:00";
        param.endTime_end = this.queryParam.endTime_end + " 23:59:59";
      }
      return filterObj(param);
    },

    batchDel: function () {

      if (!this.url.deleteBatch) {
        this.$message.error("请设置url.deleteBatch属性!")
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！');
        return;
      } else {
        var ids = "";
        for (var a = 0; a < this.selectionRows.length; a++) {
          ids += this.selectionRows[a].id + ",";
        }
        var that = this;
        this.$confirm({
          title: "确认删除",
          content: "是否删除选中数据?",
          onOk: function () {
            deleteAction(that.url.deleteBatch, {ids: ids}).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.loadData();
                that.onClearSelected();
              } else {
                that.$message.warning(res.message);
              }
            });
          }
        });
      }
    },
    handleDelete: function (id) {
      if (!this.url.delete) {
        this.$message.error("请设置url.delete属性!")
        return
      }
      var that = this;
      deleteAction(that.url.delete, {id: id}).then((res) => {
        if (res.success) {
          that.$message.success(res.message);
          that.loadData();
        } else {
          that.$message.warning(res.message);
        }
      });
    },
    handleDetail: function (record) {
      this.$refs.detailForm.title = '详情';
      this.$refs.detailForm.edit(record);
    },
    keyupEnter() {
      // eslint-disable-next-line no-unused-vars
      document.onkeydown = e => {
      }
    },
    translateCarTypeName(carTypeId){
      let result = ''
      this.CarTypeOptions.forEach(cars=>{
        if (cars.value === carTypeId)
        {
         result = cars.label
        }
      })
      return result
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
